<?php

namespace App\Traits;

use Illuminate\Http\Request;
use App\Repositories\UsersRepository;

trait Weixin
{
    public static function getOpenId(Request $request)
    {

        $appid = 'wx31332f05b81b3dba'; // 小程序APPID
        $secret = 'a0aa57b3c74639577f42ba097728c116'; // 小程序secret
        $code = $request->code;
        // var_dump($code);die;

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。    
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res, true); // 这里是获取到的信息
    }

    //是否登录
    public static function isLogin(Request $request)
    {

        if ($request->header('token')) {
            $res = self::checkToken($request);
            if (!$res) {
                return false;
            }
            $request->offsetSet('userId', $res['id']);
            $request->offsetSet('token', $res['token']);
            $request->offsetSet('nickName', $res['nickname']);
            return true;
        } else {
            return false;
        }
    }
    public static function checkToken(Request $request)
    {

        $token = $request->header('token');
        $userRes = new UsersRepository();
        $user = $userRes->infoBytoken($token);
        if ($user) {
            return self::setToken($user['id']);
        }
        return false;
    }
    public static function setToken($id, $state = '')
    {
        $newToken = md5(time() . rand(1000, 9999));
        $userRes = new UsersRepository();
        $userinfo = $userRes->info(['id'=>$id]);
        $token = '';
        if ($userinfo) {
            // $tc = time() - $userinfo['token_time'];
            // if ($tc >= 86400 || $state == 'new') {
            //     $upArr = [];
            //     $upArr['login_token'] = $newToken;
            //     $upArr['token_time'] = time();
            //     $upArr['id'] = $id;
            //     $res = $userRes->update($upArr);
            //     $token = $newToken;
            // } else {
            //     $token = $userinfo['login_token'];
            // }
            // return ['token' => $token,'nickname'=>$userinfo['nickname'], 'id' => $id];
            return ['token' => $userinfo['login_token'],'nickname'=>$userinfo['nickname'], 'id' => $id];
        }
        return false;
    }

}
